package com.naihe.anderson.sms.activity;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.entity.ContactUser;
import com.naihe.anderson.sms.entity.SignatureMsg;
import com.naihe.anderson.sms.manager.ContactMgr;
import com.naihe.anderson.sms.manager.NhSmsMgr;
import com.naihe.anderson.sms.widgets.AppPanel;

public class MakeNewSignatureActivity extends Activity implements
		OnClickListener {
	public static final int REQUEST_FRIENDCHECK_CODE = 12;

	AppPanel appPanel;
	Button create_btn;
	Button back_btn;
	Button makenewPlusFile;

	Button makenewFriend;
	Button makeriqi;
	Button maketime;
	EditText makenewForFriend;
	EditText makenewForBody;

	TextView riqi_tv;
	TextView time_tv;
	TextView grade_msg_title;

	NhSmsApp nhSmsApp;
	ContactMgr contactMgr;
	NhSmsMgr nhSmsMgr;

	private int curYear;
	private int curMonth;
	private int curDay;
	private int curHour;
	private int curMinute;

	private static final int DATEINDEX = 1;
	private static final int TIMEINDEX = 2;

	public static HashMap<String, Boolean> numberMap = new HashMap<String, Boolean>();
	private StringBuffer noContactNumbers = new StringBuffer();
	
	SignatureMsg signatureMsg;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_signature_layout);
		nhSmsApp = (NhSmsApp) getApplication();
		contactMgr = nhSmsApp.getContactMgr();
		nhSmsMgr = nhSmsApp.getNhSmsMgr();
		
		initView();
		
		if(getIntent() != null && getIntent().getExtras() != null){
			signatureMsg = (SignatureMsg) getIntent().getExtras().get("SignatureMsg");
			String friendString = getIntent().getStringExtra("makenewForFriend");
			if(!TextUtils.isEmpty(friendString)){
				numberMap.clear();
				String[] smsAddresseArray = friendString.split(",");
		        for (int i = 0; i < smsAddresseArray.length; i++) {
		        	String addressTemp  = smsAddresseArray[i];
		        	if(addressTemp.contains("<") && addressTemp.contains(">")){
		        		addressTemp = addressTemp.substring(addressTemp.indexOf("<")+1, addressTemp.indexOf(">"));
		        	} else {
		        		noContactNumbers.append(addressTemp + ",");
		        	}
		        	numberMap.put(addressTemp, true);
		        }
				makenewForFriend.setText(getIntent().getStringExtra("makenewForFriend"));
				makenewForBody.setText(getIntent().getStringExtra("makenewForBody"));
			}
		}
		
		getDateAndTime();
		
		if(signatureMsg != null) initForEditView();
	}
	
	private void initForEditView(){
		numberMap.clear();
		StringBuffer buffer = new StringBuffer();
		for(String number : signatureMsg.getContactNumbers()){
			numberMap.put(number, true);
			
			ContactUser contactUser = contactMgr.getContactUserById(contactMgr.getContactIdByPhoneNum(number));
			if(contactUser != null){
				buffer.append(contactUser.getName() + "<" + contactUser.getNumbers() + ">,");
			} else {
				noContactNumbers.append(number + ",");
				buffer.append(number + ",");
			}
		}
		makenewForFriend.setText(buffer.toString());
		makenewForBody.setText(signatureMsg.getBodyMsg());
	}

	/**
	 * 获得日期时间
	 */
	private void getDateAndTime() {
		if(signatureMsg != null){
			grade_msg_title.setText(R.string.make_edit_signature_text);
			Date date = new Date(signatureMsg.getSignatureMsgTime());
			curYear = date.getYear() + 1900;
			curMonth = date.getMonth();
			curDay = date.getDate();
			curHour = date.getHours();
			curMinute = date.getMinutes();
		} else {
			Calendar calendar = Calendar.getInstance();
			curYear = calendar.get(Calendar.YEAR);
			curMonth = calendar.get(Calendar.MONTH) + 1;
			curDay = calendar.get(Calendar.DAY_OF_MONTH);
			curHour = calendar.get(Calendar.HOUR_OF_DAY);
			curMinute = calendar.get(Calendar.MINUTE);
		}
		
		riqi_tv.setText(curYear + "-" + curMonth + "-" + curDay);
		time_tv.setText(curHour + ":" + curMinute);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == TIMEINDEX)
			return new TimePickerDialog(this, timeSetListener, curHour, curMinute, true);
		else if (id == DATEINDEX)
			return new DatePickerDialog(this, dateSetListener, curYear, curMonth, curDay);
		else
			return null;
	}

	/**
	 * 日期接口
	 */
	private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			curYear = year;
			curMonth = monthOfYear + 1;
			curDay = dayOfMonth;
			riqi_tv.setText(curYear + "-" + curMonth + "-" + curDay);
		}
	};
	/**
	 * 时间接口
	 */
	private TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			curHour = hourOfDay;
			curMinute = minute;
			time_tv.setText(hourOfDay + ":" + minute);
		}
	};

	public void initView() {

		grade_msg_title = (TextView) findViewById(R.id.grade_msg_title);
		riqi_tv = (TextView) findViewById(R.id.riqi_tv);
		time_tv = (TextView) findViewById(R.id.time_tv);

		appPanel = (AppPanel) findViewById(R.id.makenew_appPanel);
		makenewPlusFile = (Button) findViewById(R.id.makenew_plus_file);
		makenewPlusFile.setOnClickListener(this);
		makenewPlusFile.setVisibility(View.GONE);

		create_btn = (Button) findViewById(R.id.create_btn);
		create_btn.setOnClickListener(this);

		back_btn = (Button) findViewById(R.id.back_btn);
		back_btn.setOnClickListener(this);

		makenewForBody = (EditText) findViewById(R.id.makenew_forbody);
		makenewForFriend = (EditText) findViewById(R.id.makenew_for_friend);
		makenewForFriend.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View view, MotionEvent motionEvent) {
				if (appPanel.isShown())
					appPanel.setVisibility(View.GONE);
				return false;
			}
		});
		makenewForBody.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View view, MotionEvent motionEvent) {
				if (appPanel.isShown())
					appPanel.setVisibility(View.GONE);
				return false;
			}
		});

		makenewFriend = (Button) findViewById(R.id.makenew_friend);
		makenewFriend.setOnClickListener(this);

		makeriqi = (Button) findViewById(R.id.makeriqi);
		makeriqi.setOnClickListener(this);
		maketime = (Button) findViewById(R.id.maketime);
		maketime.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.makenew_friend) {
			Intent intent = new Intent(MakeNewSignatureActivity.this, FriendCheckActivity.class);
			startActivityForResult(intent, REQUEST_FRIENDCHECK_CODE);
		} else if (v.getId() == R.id.maketime) {
			showDialog(TIMEINDEX);
		} else if (v.getId() == R.id.makeriqi) {
			showDialog(DATEINDEX);
		} else if (v.getId() == R.id.makenew_plus_file) {
			if (appPanel.isShown()) {
				appPanel.setVisibility(View.GONE);
			} else {
				appPanel.setVisibility(View.VISIBLE);
				hiddenImm(v);
			}
		} else if (v.getId() == R.id.create_btn) {
			backData();
		} else if (v.getId() == R.id.back_btn) {
			numberMap.clear();
			finish();
			System.gc();
		}
	}
	
	private void backData(){
		String smsAddress =   makenewForFriend.getText().toString();
		if(TextUtils.isEmpty(smsAddress)){
			Toast.makeText(this, getResources().getString(R.string.error_msg_no_person), Toast.LENGTH_SHORT).show();
			return;
		}
		String smsBody = makenewForBody.getText().toString();
		if(TextUtils.isEmpty(smsBody)){
			Toast.makeText(this, getResources().getString(R.string.error_msg_no_body), Toast.LENGTH_SHORT).show();
			return;
		}
		
		long currentTime = new Date().getTime();
		long signatureTime = new Date(curYear - 1900, curMonth - 1, curDay, curHour, curMinute).getTime();
		if(signatureTime <= currentTime){
			Toast.makeText(this, getResources().getString(R.string.error_msg_time_pase), Toast.LENGTH_SHORT).show();
			return;
		}
		
		String[] smsAddresseArray = smsAddress.split(",");
		StringBuffer numberStrings = new StringBuffer();
		for (int i = 0; i < smsAddresseArray.length; i++) {
        	String addressTemp  = smsAddresseArray[i];
        	if(addressTemp.contains("<") && addressTemp.contains(">")){
        		addressTemp = addressTemp.substring(addressTemp.indexOf("<")+1, addressTemp.indexOf(">"));
        	}
        	numberStrings.append(addressTemp).append(";");
		}
		
		SignatureMsg msg = new SignatureMsg();
		msg.setBodyMsg(smsBody);
		msg.setContactNumbers(numberStrings.toString());
		msg.setSignatureMsgId(signatureMsg==null ? currentTime : signatureMsg.getSignatureMsgId());
		msg.setSignatureMsgStatut(SignatureMsg.SIGNATUREMSG_STATUT_COMPLETE);
		msg.setSignatureMsgTime(signatureTime);
		
		Intent aintent = new Intent(MakeNewSignatureActivity.this, SignatureMsgActivity.class);
		aintent.putExtra("SignatureMsg", msg);
		setResult(signatureMsg==null ? RESULT_OK : RESULT_FIRST_USER, aintent);
		numberMap.clear();
		this.finish();
	}

	/**
	 * 隐藏输入法
	 * 
	 * @param view
	 */
	private void hiddenImm(View view) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 截获按键事件
		if (KeyEvent.KEYCODE_BACK == keyCode) {
			if (appPanel.isShown()) {
				appPanel.setVisibility(View.GONE);
				return true;
			}
			
			numberMap.clear();
			return super.onKeyDown(keyCode, event);
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data == null || data.getExtras() == null)
			return;
		if (requestCode == REQUEST_FRIENDCHECK_CODE && resultCode == RESULT_OK) {
			String backString = data.getStringExtra("backString");
			makenewForFriend.setText(noContactNumbers.toString() + backString);
			makenewForFriend.setSelection(makenewForFriend.getText().toString().length());
		}
	}
}
